import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;

  const options = reactive({
    state: [
      {
        label: '待确认',
        value: 0,
        type: 'info',
      },
      {
        label: '已确认',
        value: 1,
        type: 'success',
      },
      // {
      //   label: '已完成',
      //   value: 3,
      //   type: 'success',
      // },
      {
        label: '已作废',
        value: 2,
        type: 'warning',
      },
    ],
    //出库状态
    inStockState: [
      {
        label: '待出库',
        value: 0,
        type: 'info',
      },
      {
        label: '部分出库',
        value: 2,
        type: 'warning',
      },
      {
        label: '完全出库',
        value: 1,
        type: 'success',
      },
    ],
    //领料类型
    backMaterialType: [
      {
        label: '生产退料',
        value: 1,
      },
    ],
    machine: [], //设备
  });
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'getMaterialBillNo',
      theadCode: 'producebackmaterialbilllist', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值表示查询全部
        likeWords: '', // 查询关键字，空值表示不进行过滤
        beginTime: '', // 查询时间范围起始值（建议格式：yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss）
        endTime: '', // 查询时间范围结束值
        onlySelf: 0, // 是否只查自己创建的数据：0 查所有；1 只查自己
        isShowDisabled: -1, // 是否显示禁用/作废数据：-1 所有；0 未作废；1 仅作废
        orderByFiled: '', // 排序字段名称，如 createTime、updateTime 等
        orderByType: 0, // 排序方式：0 倒序；1 升序
        //差异
        backMaterialType: 0, //退料类型：1生产退料，其他待定，0查询全部
        backMaterialBillState: -1, // 退料单状态：0待确认；1已确认；2已作废；3已完成，-1查询全部
        inStockState: -1, // 入库状态：0待入库；1已入库（完全）；2已拒绝；3部分入库，-1查询全部
      },
      searchThead: [
        {
          label: '物料名称',
          value: 'GoodsName',
        },
      ],
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.ProductionBusniess.GetMatchPageBackProduceMaterialBills({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                  beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
        {
          title: '扫码',
          type: 'primary',
          click: (row: any) => {
            const code: any = row.value;
            if (code) {
              proxy.$api.ProductionBusniess.GetMatchPageProduceTaskBills({
                pageIndex: 1,
                pageSize: 1,
                queryDataBaseFiled: 'produceTaskBillNo',
                likeWords: code,
                produceBillState: -1,
                taskProduceState: -1,
                materialState: -1,
                dataBillState: -2,
              })
                .then((res: any) => {
                  if (res.totalCount === 1) {
                    getPath({
                      path: `${route.path}/details`,
                      query: {
                        type: 1, //页面类型
                        produceTaskBillNo: code, //生产单号
                      },
                    });
                  } else {
                    proxy.$message('该生产单号不存在', 'error');
                  }
                  row.value = '';
                })
                .catch(() => {
                  row.value = '';
                });
            }
          },
        },
        // {
        //   title: '无单据领料',
        //   icon: 'Plus',
        //   type: 'primary',
        //   click: () => {
        //     getPath({
        //       path: `${route.path}/details`,
        //       query: {
        //         type: 1, //页面类型
        //       },
        //     });
        //   },
        // },
      ],
      //表格-列表搜索
      operation: [
        {
          title: (row: any) => {
            return row.backMaterialBillState === 0 ? '编辑' : '查看';
          },
          click: (row: any) => {
            let _query: any = {
              type: row.backMaterialBillState === 0 ? 2 : 3, //页面类型
              backMaterialID: row.backMaterialID, //
              backMaterialBillNo: row.backMaterialBillNo, //
            };
            if (row.produceTaskBillNo) {
              _query.produceTaskBillNo = row.produceTaskBillNo;
            }
            getPath({
              path: `${route.path}/details`,
              query: _query,
            });
          },
        },
        {
          title: '确认',
          disabled: (row: any) => {
            return ![0].includes(row.backMaterialBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否确认当前数据，请确认！', () => {
              proxy.$api.ProductionBusniess.SureBackProduceMaterialBill({
                backMaterialID: row.backMaterialID,
              })
                .then((res: any) => {
                  proxy.$message('确认成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '撤回',
          disabled: (row: any) => {
            return ![1].includes(row.backMaterialBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否撤回当前数据，请确认！', () => {
              proxy.$api.ProductionBusniess.RevokeBackProduceMaterialBill({
                backMaterialID: row.backMaterialID,
              })
                .then((res: any) => {
                  proxy.$message('撤回成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '作废',
          disabled: (row: any) => {
            return ![0].includes(row.backMaterialBillState);
          },
          click: (row: any) => {
            proxy.$messageInputBox('请填写作废原因！', (value: string) => {
              proxy.$api.ProductionBusniess.CancelBackProduceMaterialBill({
                backMaterialID: row.backMaterialID,
                cancelReason: value,
              })
                .then((res: any) => {
                  proxy.$message('作废成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '退料单',
          children: [
            {
              title: '打印',
              disabled: (row: any) => {
                return [0].includes(row.getMaterialBillState);
              },
              click: (row: any) => {
                proxy.$DownLoadTemp(
                  {
                    templateTypeCode: 'MBLX0013', //	模板类型编号
                    condition: {
                      BackMaterialBillNo: row.backMaterialBillNo,
                    },
                  },
                  1,
                  dataInfo,
                );
              },
            },
            {
              title: '下载',
              disabled: (row: any) => {
                return [0].includes(row.getMaterialBillState);
              },
              click: (row: any) => {
                proxy.$DownLoadTemp(
                  {
                    templateTypeCode: 'MBLX0013', //	模板类型编号
                    condition: {
                      BackMaterialBillNo: row.backMaterialBillNo,
                    },
                  },
                  3,
                  dataInfo,
                );
              },
            },
          ],
        },
        {
          title: '删除',
          disabled: (row: any) => {
            return ![0, 2].includes(row.backMaterialBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.ProductionBusniess.DeleteBackProduceMaterialBill({
                backMaterialID: row.backMaterialID,
              })
                .then((res: any) => {
                  proxy.$message('删除成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
      ],
    },
  });
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.ProductionBusniess.GetMatchPageBackProduceMaterialBills({
      ..._table.search,
    })
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[], thead?: any[]) => {
    proxy.$exportData(
      {
        thead: thead || dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  onMounted(() => {});
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options };
}
